# -*- coding: utf-8 -*-

# Copyright 2011 Google Inc. All Rights Reserved.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from google.appengine.dist import use_library
use_library('django', '1.2')

import cgi
import datetime
import logging
import os

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util

import model

class GuestPageDataHandler(webapp.RequestHandler):
    def get(self, guest_id):
        guest = model.Guest.get_by_key_name(
            guest_id, parent=model.main_event)
        if not guest:
            self.redirect('/guest/home/')
        else:
            if not guest.read_ts:
                guest.read_ts = datetime.datetime.now()
                guest.put()
            message = ''
            if self.request.get('op') == 'rsvp':
                if self.request.get('status') == 'ok':
                    message = ('Parabens, presença confirmada. Vejo '
                               'você na festa, não vai esquecer, hein.')
            
            form = model.GuestForm(instance=guest)
            template_values = {
                'event': model.main_event,
                'guest': guest,
                'm': message,
                'form': form,
                'id': guest_id}
            path = os.path.join(os.path.dirname(__file__), 'guest.html')
            self.response.out.write(template.render(path, template_values))


class RSVPDataHandler(webapp.RequestHandler):
    def post(self, guest_id):
        guest = model.Guest.get_by_key_name(
            guest_id, parent=model.main_event)
        if not guest:
            self.redirect('/guest/%s/home?op=rsvp&status=notfound' % (
                    guest_id))
        else:
            form = model.GuestForm(data=self.request.POST,
                                       instance=guest)
            status = 'error'
            if form.is_valid():
                status = 'ok'
                form.save(commit=False)
                if not guest.rsvp_ts:
                    guest.rsvp_ts = datetime.datetime.now()
                guest.put()

            self.redirect('/guest/%s/home?op=rsvp&status=%s' % (
                    guest_id, status))

class CookieDataHandler(webapp.RequestHandler):
    def get(self, guest_id):
        self.response.headers.add_header(
            'Set-Cookie', 'guestid=%s; expires=%s; path=/guest; '
            'httponly' % (
                guest_id, model.main_event.end_ts.strftime(
                    '%a, %d %b %Y %H:%M:%S GMT')))
        self.redirect('http://goingtoswitzerland.menderico.com.br/')
           
class UnknownGuestHandler(webapp.RequestHandler):
    def get(self):
        form = model.GuestForm()
        template_values = {
            'event': model.main_event, 'guest': None,
            'm': '', 'form': form, 'id': ''}
        path = os.path.join(os.path.dirname(__file__), 'guest.html')
        self.response.out.write(template.render(path, template_values))

class RedirectHandler(webapp.RequestHandler):
    def get(self):
        if 'guestid' in self.request.cookies:
            self.redirect('/guest/%s/home' % (
                    self.request.cookies['guestid']))
        else:
            self.redirect('/guest/home/')

def main():
    application = webapp.WSGIApplication(
        [('/guest/', RedirectHandler),
         ('/guest/home/', UnknownGuestHandler),
         ('/guest/(.*)/', CookieDataHandler),
         ('/guest/(.*)/rsvp', RSVPDataHandler),
         ('/guest/(.*)/home', GuestPageDataHandler)])
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
